package com.example.smartagrisys.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件控制器，用于访问上传的文件
 */
@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Value("${file.upload.path:/tmp/uploads/}")
    private String uploadPath;

    /**
     * 获取文件内容
     *
     * @param directory 目录名称
     * @param date 日期路径
     * @param filename 文件名
     * @return 文件内容
     */
    @GetMapping("/{directory}/{date}/{filename:.+}")
    public ResponseEntity<Resource> getFile(
            @PathVariable String directory,
            @PathVariable String date,
            @PathVariable String filename) {
        
        try {
            String filePath = uploadPath + directory + "/" + date + "/" + filename;
            Path path = Paths.get(filePath);
            
            // 检查文件是否存在
            if (!Files.exists(path)) {
                log.error("文件不存在: {}", filePath);
                return ResponseEntity.notFound().build();
            }
            
            // 确定媒体类型
            String contentType = Files.probeContentType(path);
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            
            // 创建资源并返回
            Resource resource = new FileSystemResource(new File(filePath));
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"")
                    .body(resource);
                    
        } catch (IOException e) {
            log.error("获取文件失败", e);
            return ResponseEntity.badRequest().build();
        }
    }
} 